// 云函数入口文件
const cloud = require('wx-server-sdk')

cloud.init({
	env: cloud.DYNAMIC_CURRENT_ENV
})

const db = cloud.database()
const _ = db.command

// 云函数入口函数
exports.main = async (event, context) => {
	const {
		state,
		UID,
		_id
	} = event

	// 先获取字段的数组数据
	const info = await db.collection('usersInfo').where({
		'profile.student_ID': UID
	}).get()

	// 判断当前删除的页面状态
	if (state == 0) {
		
		// 如果是 我的发布-已发布
		const index = info.data[0].published.indexOf(_id)
		info.data[0].published.splice(index, 1)
		await db.collection('usersInfo').where({
			'profile.student_ID': UID
		}).update({
			data: {
				published: info.data[0].published
			}
		})
		
		return await db.collection('lost_and_found_infos').doc(_id).remove()
		
	} else if (state == 1) {
		
		// 如果是 我的发布-已被找回
		const index = info.data[0].recovered.indexOf(_id)
		info.data[0].recovered.splice(index, 1)
		return await db.collection('usersInfo').where({
			'profile.student_ID': UID
		}).update({
			data: {
				recovered: info.data[0].recovered
			}
		})
		
	} else if (state == 2) {
		
		// 如果是 我的找回
		const index = info.data[0].get_back.indexOf(_id)
		info.data[0].get_back.splice(index, 1)
		return await db.collection('usersInfo').where({
			'profile.student_ID': UID
		}).update({
			data: {
				get_back: info.data[0].get_back
			}
		})
		
	}

}
